<template>
  <view class="w100  pl-30 pr-30 pb-20">
    <uni-card margin="0">
      <view class="inforClass pt-20">任务信息</view>
      <view class="w100 rowsb rowsm h-100 pl-20 pr-20">
        <view class="w100 rowsb rowsm h-80 trt border-botm">
          <view class="fs-28 col333 fw-b rowsb rowsm" style="white-space: nowrap;">
            <view style="color: red">*</view>
            <view>实践任务名称：</view>
          </view>
          <input type="text" placeholder="请输入实践任务名称" placeholder-class="fs-28 col888" v-model="practiceData.taskName">
        </view>
      </view>

      <!-- 实践类型： -->
      <view class="typeWarp pl-20 pr-20">
        <view class="practiceType border-botm">
          <view class="fs-28 col333 fw-b"><text style="color: red">*</text>实践类型：</view>
          <picker mode="selector" range-key="text" :range="practiceType" @change="changeScore">
            <view class="fs-30" :style="{ 'color': scoreIndex !== null ? '#000' : '#a9a9a9' }">{{ scoreIndex !== null &&
              scoreIndex >= 0 ?
              practiceType[scoreIndex].text : '请选择类型' }}</view>
          </picker>
        </view>
      </view>
      <view class="typeWarp pl-20 pr-20">
        <view class="practiceType border-botm">
          <view class="fs-28 col333 fw-b"><text style="color: red">*</text>积分上限：</view>
          <picker mode="selector" range-key="text" :range="integralList" @change="changeIntegral">
            <view class="fs-30" :style="{ 'color': integralIndex !== null ? '#000' : '#a9a9a9' }">{{ integralIndex !==
              null ?
              integralList[integralIndex] : '请设置积分' }}</view>
          </picker>
        </view>
      </view>
      <view class="typeWarp pl-20 pr-20">
        <view class="practiceType border-botm">
          <view class="fs-28 col333 fw-b"><text style="color: red">*</text>任务时间：</view>
          <uni-datetime-picker v-model="range" type="daterange" @change="changeTime" />
        </view>
      </view>
      <view class="typeWarp pl-20 pr-20">
        <view class="practiceType border-botm">
          <view class="fs-28 col333 fw-b"><text style="color: red; visibility: hidden;">*</text>所属学期：</view>
          <uni-data-select v-if="semesterList.length > 0" style="width: 70%;" v-model="practiceData.semesterConfigId"
            :localdata="semesterList" :clear="false"></uni-data-select>
          <view v-else style="flex: 1"> 请选择任务时间 </view>
        </view>
      </view>
      <view class="w100 rowsb rowsm h-100 pl-20 pr-20">
        <view class="w100 rowsb rowsm h-80 trt border-botm">
          <view class="fs-28 col333 fw-b rowsb rowsm" style="white-space: nowrap;">
            <view style="color: red; visibility: hidden;">*</view>
            <view>若审核不通过扣除积分数：</view>
          </view>
          <input type="text" @input="handleInputPassPoints" placeholder="请输入" placeholder-class="fs-28 col888"
            v-model="practiceData.noPassPoints">
        </view>
      </view>
    </uni-card>

    <uni-card padding="0">
      <view class="inforClass pt-20">参与设置</view>

      <view class="typeWarp pl-20 pr-20">
        <view class="practiceType border-botm">
          <view class="fs-28 col333 fw-b"><text style="color: red">*</text>参与方式：</view>
          <picker mode="selector" range-key="text" :range="participaList" @change="changeWay">
            <view class="fs-30" style="color: #000">
              {{ participaList[practiceData.participationWay - 1].text }}
            </view>
          </picker>
        </view>
      </view>
      <view class="typeWarp pl-20 pr-20" v-if="practiceData.participationWay != 2">
        <view class="practiceType border-botm">
          <view class="fs-28 col333 fw-b"><text style="color: red">*</text>任务次数：</view>
          <picker mode="selector" range-key="text" :range="taksnNumList" @change="changeTaksnNum">
            <view class="fs-30" :style="{ 'color': taksnNumIndex !== null ? '#000' : '#a9a9a9' }">{{ taksnNumIndex !==
              null ?
              taksnNumList[taksnNumIndex] : '请设置次数' }}</view>
          </picker>
        </view>
      </view>
      <view v-if="practiceData.participationWay == 2">
        <view class="typeWarp pl-20 pr-20">
          <view class="practiceType border-botm">
            <view class="fs-28 col333 fw-b"><text style="color: red">*</text>报名审核：</view>
            <picker mode="selector" range-key="text" :range="applyCheckList" @change="changeApplyCheck">
              <view class="fs-30" :style="{ 'color': practiceData.applyCheck !== null ? '#000' : '#a9a9a9' }">
                {{ practiceData.applyCheck != null ? applyCheckList[practiceData.applyCheck].text : '请设置报名审核' }}</view>
            </picker>
          </view>
        </view>
        <view class="typeWarp pl-20 pr-20">
          <view class="practiceType border-botm">
            <view class="fs-28 col333 fw-b"><text style="color: red">*</text>报名时间：</view>
            <uni-datetime-picker v-model="dateRangeApply" type="daterange" />
          </view>
        </view>
        <view class="w100 rowsb rowsm h-100 pl-20 pr-20">
          <view class="w100 rowsb rowsm h-80 trt border-botm">
            <view class="fs-28 col333 fw-b rowsb rowsm" style="white-space: nowrap;">
              <view style="color: red">*</view>
              <view>人数限制：</view>
            </view>
            <input type="text" placeholder="请设置人数限制" placeholder-class="fs-28 col888"
              v-model="practiceData.peoplesNumberAstrict" @input="handleInput">
          </view>
        </view>
        <view class="w100 rowsb rowsm h-100 pl-20 pr-20">
          <view class="w100 rowsb rowsm h-80 trt border-botm">
            <view class="fs-28 col333 fw-b rowsb rowsm" style="white-space: nowrap;">
              <view>爽约扣除积分数：</view>
            </view>
            <input type="text" placeholder="请设置扣除积分数" placeholder-class="fs-28 col888"
              v-model="practiceData.applyPassCancelPoints" @input="handleInputPoints">
          </view>
        </view>
      </view>
      <view class="w100 rowsb rowsm h-100 pl-20 pr-20">
        <view class="w100 rowsb rowsm h-80 trt border-botm">
          <view class="fs-28 col333 fw-b rowsb rowsm" style="white-space: nowrap;">
            <view style="color: red; visibility: hidden;">*</view>
            <view>学生范围:</view>
          </view>
          <button class="fs-24" style="margin-left: 15px; " @click="showPicker">选择学生({{ studentIds.length }})</button>
        </view>
      </view>

      <ba-tree-picker ref="treePicker" :multiple='true' :selectedData="selectedData" @select-change="selectChange"
        title="选择学生" :localdata="modifiedTreeData" valueKey="value" textKey="label" childrenKey="children" />
    </uni-card>
    <uni-card padding="0">
      <view class="inforClass pt-20">任务要求</view>
      <textarea class="fw-n" style="width: 100%" v-model="practiceData.taskRequire" placeholder="请输入任务要求(必填)"></textarea>
    </uni-card>
    <uni-card padding="0">
      <view class="inforClass pt-20">注意事项</view>
      <textarea style="width: 100%" v-model="practiceData.mattersNeedAttention" placeholder="请输入注意事项"></textarea>
    </uni-card>
    <uni-card padding="0">
      <view class="inforClass pt-20">附件</view>
      <view class="w100 pl-24 pr-24 mb-20">
        <view class="w100 h-120 br-10 rows rowsm pl-40 mb-10" style="background-color: #F7F6FA;" @click="choseFile">
          <image src="/static/icon_cs.png" class="w-50 h-60 mr-20" mode=""></image>
          <!-- <view class="fs-26 col888">（可上传word、pdf、excel、图片、视频）</view> -->
          <view class="fs-26 col888">
            <view class="fs-24">须知: 图片最多6张、文件最多1个最大10M、视频最多1个最大100M,且附件为必填项</view>
            <view>（可上传word、pdf、图片、视频）</view>
          </view>
        </view>

        <view class="w100 h-140 br-10 rowsb rowsm pl-40" style="background-color: #F7F6FA;"
          v-for="(item, index) in fileList" :key="index">
          <view class="rows rowsm w-350">
            <image src="/static/file.png" class="w-60 h-60 mr-20" mode=""></image>
            <view class="fs-28 col888 w100 one_overflow">{{ item.fileName }}</view>
          </view>
          <view class="w-120 h-60 br-30 rowsc rowsm colfff fs-24 mr-10"
            style="background: linear-gradient(to bottom,#4897FF,#4878FF);" @click="handelDelete(item)">删除</view>
        </view>
      </view>
    </uni-card>
    <view class="w100 rowsa rowsm mt-20 mb-20"
      v-if="permissions.find(v => v == '*:*:*') || permissions.find(v => v == 'project:task:add')">
      <view class="w-202 h-84 br-42 rowsc rowsm colfff" style="background: linear-gradient(to bottom,#64606b,#64606b);"
        @click="submit(0)">
        保存
      </view>
      <view class="w-202 h-84 br-42 rowsc rowsm colfff" style="background: linear-gradient(to bottom,#4897FF,#4878FF);"
        @click="submit(1)">
        发布
        <!-- v-if="(permissions.find(v => v == '*:*:*') || permissions.find(v => v == 'project:task:publish'))" -->
      </view>
    </view>
  </view>
</template>

<script>
import { Base64 } from 'js-base64';
export default {
  data() {
    return {
      practiceData: {
        taskName: '',
        taskRequire: '',
        mattersNeedAttention: '',
        practiceType: '',
        taskNumber: '',
        pointsCap: '',
        faceXy: '',
        faceZy: '',
        faceBj: '',
        semesterConfigId: '',
        participationWay: 1,
        applyCheck: null,
        peoplesNumberAstrict: 1
      },
      practiceType: [],
      integralIndex: null,
      integralList: [50, 100, 150, 200, 250, 300, 350, 400],
      taksnNumIndex: 0,
      taksnNumList: [1, 2, 3, 4, 5], // 任务次数
      show: false,
      endTimeShow: false,
      name: '',
      startTimePoke: '',
      startTime: '',
      endTime: '',
      endTimePoke: '',
      type: '1',
      file: '',
      fileType: '',
      fileName: '',
      fileList: [],
      scoreIndex: null,
      proxyList: [],
      proxyIndex: null,
      prozyAddList: [],
      prozyAddIndex: null,
      probjAddList: [],
      probjAddIndex: null,
      pronjAddList: [],
      pronjAddIndex: null,
      taskId: null,  // 任务id
      permissList: [],
      proxyName: '',
      prozyName: '',
      probjName: '',
      pronjName: '',
      range: [],
      permissions: [],
      oldProxy: null,
      oldProzy: null,

      participaList: [
        { value: '1', text: '指定学生参与' },
        { value: '2', text: '学生自选报名' }
      ],
      applyCheckList: [
        { value: '0', text: '无需审核，直接参与' },
        { value: '1', text: '需要审核通过后参与' }
      ],
      studentIds: [],
      listData: [],
      semesterList: [],
      dateRangeApply: [],
      selectedData: [],
    };
  },

  onLoad(e) {
    if (uni.getStorageSync('flag') == 'teacher') {
      this.$tools.axiosFromToken('POST', 'sysUser/getById', {}, '加载中').then(res => {
        if (res.code != 200) return this.$tools.showtt(res.msg)
        let getAllInfo = { ...res.data, user: JSON.parse(Base64.decode(res.data.user)) }
        uni.setStorageSync('getInfo', getAllInfo);
        this.permissions = res.data.permissions.flat() || [];
      })
    }
    // this.permissList = uni.getStorageSync('getInfo').practiceTypes;
    // // this.permissions = uni.getStorageSync('getInfo').permissions.flat() || [];
    // const typeMap = {
    //   1: { value: '1', text: '劳动教育' },
    //   2: { value: '2', text: '职业素养' },
    //   3: { value: '3', text: '应急安全' },
    //   4: { value: '4', text: '思政实践' },
    //   5: { value: '5', text: '创新创业' }
    // };
    // this.permissList.forEach(v => {
    //   if (typeMap[v]) {
    //     this.practiceType.push(typeMap[v]);
    //   }
    // });

    if (e.id) {
      uni.setNavigationBarTitle({
        title: '修改实践任务'
      })
    } else {
      // this.getListProxy();
      // this.getListProzy();
      // this.getListProbj();
      // this.getListPronj();
    }
  },
  computed: {
    modifiedTreeData() {
      return this.listData.map(node => {
        return this.processNode(node);
      });
    }
  },
  created() {
    this.getAllBj();
    this.getTypeCongfigList();
    // this.getListProxy();
    if (this.$route.query.id) {
      this.taskId = this.$route.query.id;
      this.getInfo();
    }
  },
  methods: {
    getTypeCongfigList() {
      this.$tools.axiosFromToken('GET', 'project/practice/type/config/list?pageNum=1&pageSize=50', {}, '加载中').then(res => {
        if (res.code != 200) return this.$tools.showtt(res.msg)
        res.rows.forEach(item => {
          this.practiceType.push({ text: item.name, value: item.id })
        })
      })
    },
    changeTime(e) {
      this.range = e;
      this.semesterList = [];
      if (e.length > 0) {
        this.$tools.axiosFromToken('GET', 'project/semester/config/list', { startTime: e[0] + ' 00:00:00' }, '加载中').then(res => {
          if (res.code == 200) {
            const semesterList = res.rows.filter(item => {
              if (
                (new Date(e[1] + ' 23:59:59').getTime() >= new Date(item.startTime).getTime() && new Date(e[1] + ' 23:59:59').getTime() <= new Date(item.endTime).getTime())
                ||
                (new Date(e[0] + ' 00:00:00').getTime() <= new Date(item.startTime).getTime() && new Date(e[1] + ' 23:59:59').getTime() <= new Date(item.endTime).getTime() && new Date(e[1] + ' 23:59:59').getTime() >= new Date(item.startTime).getTime())
                ||
                (new Date(e[0] + ' 00:00:00').getTime() >= new Date(item.startTime).getTime() && new Date(e[1] + ' 23:59:59').getTime() >= new Date(item.endTime).getTime())
              ) {
                return item;
              }
            });
            this.$nextTick(() => {
              this.semesterList = semesterList.map(item => ({ value: String(item.id), label: item.name, text: item.name }));
              this.practiceData.semesterConfigId = this.semesterList.length > 0 ? this.semesterList[0].value : null;
            });
          }
        });
      } else {
        this.practiceData.semesterConfigId = null;
      }
    },
    hideKeyboard() {
      uni.hideKeyboard();
    },
    // 显示选择器
    showPicker() {
      this.$nextTick(() => {
        this.$refs.treePicker._show();
      })
    },
    getAllBj() {
      this.$tools.axiosFromToken('POST', 'prouser/getStudentTree', {}, '加载中').then(res => {
        if (res.code != 200) return this.$tools.showtt(res.msg)
        this.listData = [];
        this.listData = res.data;
      })
    },
    //监听选择（ids为数组）
    selectChange(ids, names) {
      this.xyIdList = [];
      this.zyIdList = [];
      this.bjIdList = [];
      this.studentIds = [];
      const selectedNodesWithParents = [];
      ids.forEach(value => {
        const nodeWithParents = this.getNodeWithParents(this.modifiedTreeData, value.id);
        if (nodeWithParents) {
          selectedNodesWithParents.push(nodeWithParents);
        }
      });
      selectedNodesWithParents.forEach(v => {
        v.forEach(value => {
          if (value.split('-')[1] == 'xy') {
            this.xyIdList.push(value.split('-')[0])
          }
          if (value.split('-')[1] == 'zy') {
            this.zyIdList.push(value.split('-')[0])
          }
          if (value.split('-')[1] == 'bj') {
            this.bjIdList.push(value.split('-')[0])
          }
          if (value.split('-')[1] == 'xs') {
            this.studentIds.push(value.split('-')[0])
          }
        });
      })
    },

    getNodeWithParents(data, value) {
      let currentNode = null;
      let parents = [];
      let children = [];

      const findNode = (nodes, value) => {
        for (const node of nodes) {
          // 如果找到节点，记录当前节点
          if (node.value === value) {
            currentNode = node;
            return true;
          }
          // 检查子节点
          if (node.children && findNode(node.children, value)) {
            parents.push(node.value);
            return true;
          }
        }
        return false;
      };

      const getAllChildren = (node) => {
        if (node.children) {
          children.push(...node.children); // 将当前节点的子节点加入到 children 数组中
          for (const child of node.children) {
            getAllChildren(child); // 递归获取子节点的子节点
          }
        }
      };

      findNode(data, value);

      if (currentNode) {
        parents.unshift(currentNode.value); // 将当前节点添加到父节点路径的开头
        getAllChildren(currentNode); // 获取当前节点的所有子节点
      }

      return [...parents, ...children.map((child) => child.value)];
    },
    handleInputPassPoints(val) {
      this.$nextTick(() => {
        this.practiceData.noPassPoints = val.detail.value.replace(/[^\d]/g, '');
      });
    },
    handleInput(val) {
      this.$nextTick(() => {
        const filteredValue = val.detail.value.replace(/[^\d]/g, '');
        // this.practiceData.peoplesNumberAstrict = val.detail.value.replace(/[^\d]/g, '');
        if (!filteredValue || Number(filteredValue) === 0) {
          this.practiceData.peoplesNumberAstrict = 1;
          return;
        }
        if (Number(filteredValue) > this.studentIds.length) {
          this.practiceData.peoplesNumberAstrict = this.studentIds.length;
          return;
        }
        this.practiceData.peoplesNumberAstrict = val.detail.value.replace(/[^\d]/g, '');
      });
    },
    handleInputPoints(val) {
      this.$nextTick(() => {
        this.practiceData.applyPassCancelPoints = val.detail.value.replace(/[^\d]/g, '');
      });
    },
    processNode(node) {
      if (node.type === 'xy') {
        return {
          type: node.type,
          label: node.xyName,
          value: node.xyId + '-' + node.type,
          children: node.zyChildList ? node.zyChildList.map(child => this.processNode(child)) : []
        };
      } else if (node.type === 'zy') {
        return {
          type: node.type,
          label: node.zyName,
          value: node.zyId + '-' + node.type,
          children: node.bjChildList ? node.bjChildList.map(child => this.processNode(child)) : []
        };
      } else if (node.type === 'bj') {
        return {
          type: node.type,
          label: node.bjName,
          value: node.bjId + '-' + node.type,
          children: node.studentChildList ? node.studentChildList.map(child => this.processNode(child)) : []
        };
      } else {
        return {
          type: node.type,
          label: node.userName + '(' + node.stNumber + ')',
          value: node.userId + '-' + node.type,
          children: []
        };
      }
    },
    getInfo() {
      this.$tools.axiosFromToken('GET', `teacher/project/task/${this.taskId}`, {}, '加载中').then(res => {
        if (res.code != 200) return this.$tools.showtt(res.msg)
        this.practiceData = { ...res.data };
        this.fileList = res.data.fileList;
        this.range = [this.practiceData.startTime.slice(0, 10), this.practiceData.endTime.slice(0, 10)];
        this.changeTime(this.range);
        if (this.practiceData.applyStartTime) {
          this.dateRangeApply = [this.practiceData.applyStartTime.slice(0, 10), this.practiceData.applyEndTime.slice(0, 10)];
        }
        this.scoreIndex = this.practiceType.findIndex(v => v.value == this.practiceData.practiceType);
        this.integralIndex = this.integralList.findIndex(v => v == this.practiceData.pointsCap);
        this.taksnNumIndex = this.taksnNumList.findIndex(v => v == this.practiceData.taskNumber);
        this.studentIds = res.data.studentIds;

        res.data.faceXy.split(',').forEach(xy => {
          this.selectedData.push(String(xy) + '-xy');
        });
        res.data.faceZy.split(',').forEach(zy => {
          this.selectedData.push(String(zy) + '-zy');
        });
        res.data.faceBj.split(',').forEach(bj => {
          this.selectedData.push(String(bj) + '-bj');
        });
        res.data.studentIds.forEach(xs => {
          this.selectedData.push(String(xs) + '-xs');
        });
      })
    },
    // 查询学院
    getListProxy() {
      this.$tools.axiosFromToken('GET', 'project/proxy/listTotal', {}, '加载中').then(res => {
        if (res.code != 200) return this.$tools.showtt(res.msg)

        if (this.taskId && this.practiceData.faceXy) {
          const xyId = this.practiceData.faceXy.split(',');
          res.rows.forEach(v => {
            xyId.forEach(y => {
              if (v.id == y) {
                v.check = true;
              }
            })
          })
          // this.proxyIndex = this.proxyList.findIndex(v => v.id == this.practiceData.faceXy) >= 0 ? this.proxyList.findIndex(v => v.id == this.practiceData.faceXy) : null;
        }
        this.proxyList = res.rows;
        if (res.rows.length > 0) {
          this.proxyList.unshift({ name: '全部', id: 999999, check: this.taskId ? false : true });
        }

        this.$forceUpdate();
      })
    },
    // 劳动开始时间
    confirmStartTime(e) {
      if (this.endTimePoke && this.endTimePoke < e.value) {
        this.$tools.showtt('开始时间大于结束时间,请重新选择')
        return
      }
      this.startTimePoke = e.value;
      const formattedDate = new Date(e.value).toLocaleDateString(); // 转为本地时间字符串
      this.startTime = formattedDate.split('/').join("-");
      this.show = false;

    },
    //  劳动结束时间
    confirmEndTime(e) {
      if (this.startTimePoke && this.startTimePoke > e.value) {
        this.$tools.showtt('结束时间小于开始时间,请重新选择')
        return
      }
      this.endTimePoke = e.value;
      const formattedDate = new Date(e.value).toLocaleDateString(); // 转为本地时间字符串
      this.endTime = formattedDate.split('/').join("-");
      this.endTimeShow = false;
    },
    changeScore(e) {
      this.scoreIndex = e.detail.value;
      this.taskType = this.practiceType[this.scoreIndex].text;
      this.practiceData.practiceType = this.practiceType[this.scoreIndex].value;

    },
    changeIntegral(e) {
      this.integralIndex = e.detail.value
    },
    changeTaksnNum(e) {
      this.taksnNumIndex = e.detail.value
    },
    changeWay(e) {
      this.practiceData.participationWay = e.detail.value + 1;
    },
    changeApplyCheck(e) {
      this.practiceData.applyCheck = e.detail.value;
    },
    changeProxy(x, y, z) {
      if (JSON.stringify(this.oldProxy) === JSON.stringify(y)) return;
      this.oldProxy = y;
      let allId = [];
      if (y.find(v => v == 999999)) {
        this.proxyList.slice(1).forEach(id => allId.push(id.id))
      } else {
        allId = y;
      }
      this.practiceData.faceXy = allId.join(",");
      this.prozyAddList = [];
      this.probjAddList = [];
      if (allId.length > 0) {
        this.getListProzy(allId);
      }
    },
    changeProzy(x, y, z) {
      if (JSON.stringify(this.oldProzy) === JSON.stringify(y)) return;
      this.oldProzy = y;
      let allId = [];
      if (y.find(v => v == 99999999)) {
        this.prozyAddList.slice(1).forEach(id => allId.push(id.id))
      } else {
        allId = y;
      }
      this.practiceData.faceZy = allId.join(",");
      this.probjAddList = [];
      if (allId.length > 0) {
        this.getListProbj(allId);
      }
    },
    changeProbj(x, y, z) {
      let allId = [];
      if (y.find(v => v == 9999999999)) {
        this.probjAddList.slice(1).forEach(id => allId.push(id.id))
      } else {
        allId = y;
      }
      this.practiceData.faceBj = allId.join(",");
    },
    changePronj(x, y, z) {
      // this.pronjAddIndex = e.detail.value
      this.probjAddList = [];
      let allId = [];
      if (y.find(v => v == 999999999999)) {
        this.pronjAddList.slice(1).forEach(id => allId.push(id.name))
      } else {
        allId = z;
      }
      this.practiceData.faceNj = allId.join(",");
      if (this.prozyAddList.length > 1) {
        let zyIdList = [];
        this.prozyAddList.slice(1).forEach(id => zyIdList.push(id.id))
        this.getListProbj(this.practiceData.faceZy == '' ? zyIdList : this.practiceData.faceZy.split(','));
      }
    },
    getListProzy(id) {
      const data = {};
      this.probjAddList = [];
      if (id) {
        data.xyIds = id;
      }
      this.$tools.axiosFromToken('GET', 'project/prozy/listTotal', data, '加载中').then(res => {
        if (res.code != 200) return this.$tools.showtt(res.msg)
        if (this.taskId && this.practiceData.faceZy) {
          const zyId = this.practiceData.faceZy.split(',');
          res.rows.forEach(v => {
            zyId.forEach(y => {
              if (v.id == y) {
                v.check = true;
              }
            })
          })
          // this.prozyAddIndex = this.prozyAddList.findIndex(v => v.id == this.practiceData.faceZy) >= 0 ? this.prozyAddList.findIndex(v => v.id == this.practiceData.faceZy) : null;
        }
        this.prozyAddList = res.rows;
        if (res.rows.length > 0) {
          this.getListProbj(this.prozyAddList.map(v => v.id).join(','));
          this.prozyAddList.unshift({ name: '全部', id: 99999999, check: this.taskId ? false : true });
        }

      })
    },
    getListProbj(id) {
      let data = {};
      // if (id) {
      data.zyIds = id;
      data.njIds = this.practiceData.faceNj;
      // }
      if (id == undefined && data.njIds == undefined) {
        data = {}
      }
      if (id && data.njIds == undefined) {
        data.zyIds = id;
        delete data.njIds;
      }
      if (id == undefined && data.njIds) {
        delete data.zyIds;
      }
      this.$tools.axiosFromToken('GET', 'project/probj/listTotal', data, '加载中').then(res => {
        if (res.code != 200) return this.$tools.showtt(res.msg)
        if (this.taskId && this.practiceData.faceBj) {
          const bjId = this.practiceData.faceBj.split(',');
          res.rows.forEach(v => {
            bjId.forEach(y => {
              if (v.id == y) {
                v.check = true;
              }
            })
          })
          // this.probjAddIndex = this.probjAddList.findIndex(v => v.id == this.practiceData.faceBj) >= 0 ? this.probjAddList.findIndex(v => v.id == this.practiceData.faceBj) : null;
        }
        this.probjAddList = [];
        res.rows.forEach(v => {
          this.probjAddList.push(v);
        })
        if (res.rows.length > 0) {
          this.probjAddList.unshift({ name: '全部', id: 9999999999, check: this.taskId ? false : true });
        }
      })
    },

    getListPronj() {
      this.$tools.axiosFromToken('GET', 'project/class/selectorForList', {}, '加载中').then(res => {
        if (res.code != 200) return this.$tools.showtt(res.msg)
        if (this.taskId && this.practiceData.faceNj) {
          const njId = this.practiceData.faceNj.split(',');
          res.rows.forEach(v => {
            njId.forEach(y => {
              if (v.name == y) {
                v.check = true;
              }
            })
          })
          // this.pronjAddIndex = this.pronjAddList.findIndex(v => v.name == this.practiceData.faceNj) >= 0 ? this.pronjAddList.findIndex(v => v.name == this.practiceData.faceNj) : null;
        }
        this.pronjAddList = res.rows;
        if (res.rows.length > 0) {
          this.pronjAddList.unshift({ name: '全部', id: 999999999999, check: this.taskId ? false : true });
        }
      })
    },
    handelDelete(item) {
      this.fileList.splice(this.fileList.findIndex(v => v.fileName === item.fileName), 1)
    },
    choseFile() {
      if (this.fileList.length === 5) return this.$tools.showtt('最多上传5个文件');
      let currentTotalSize = this.fileList.reduce((acc, item) => {
        return acc + item.size;
      }, 0);
      // const type = this.taskType == '劳动教育' ? 'ldjy' : this.taskType == '职业素养' ? 'zysj' : this.taskType == '应急安全' ? 'yjaqjy' : this.taskType == '思想实践教育' ? 'sxsjjy' : 'cxcyjy'
      uni.showActionSheet({
        itemList: ['图片', '文件', '视频'],
        success: (index, e) => {
          if (index.tapIndex === 0) {
            uni.chooseImage({
              count: 5 - this.fileList.length,
              sizeType: ['compressed'], // 选择压缩后的图片
              success: (res) => {
                res.tempFilePaths.forEach(item => {
                  // // 检查单个文件大小，6MB = 6 * 1024 * 1024
                  // if (res.tempFiles[0].size > 6 * 1024 * 1024) {
                  //   this.$tools.showtt('图片大小不能超过6MB');
                  //   return;
                  // }
                  // // 检查总文件大小
                  // currentTotalSize += res.tempFiles[0].size;
                  // if (currentTotalSize > 6 * 1024 * 1024) {
                  //   this.$tools.showtt('附件总大小不能超过6MB');
                  //   currentTotalSize -= res.tempFiles[0].size; // 回退当前大小
                  //   return;
                  // }
                  // this.compressImage(item).then((compressedFilePath) => {
                  uni.uploadFile({
                    url: this.$tools.httpOne + 'utils/ossUpload',
                    filePath: item,
                    name: 'file',
                    header: {
                      'Authorization': "Bearer " + sessionStorage.getItem('token')
                      // 'token': sessionStorage.getItem('token')
                    },
                    success: (res1) => {
                      if (JSON.parse(res1.data).code === 200) {
                        this.fileList.push({
                          fileName: JSON.parse(res1.data).originalFilename,
                          // fileType: JSON.parse(res1.data).originalFilename.split('.')[1],
                          fileType: '图片',
                          file: JSON.parse(res1.data).url,
                          // type: type,
                        });
                      } else {
                        this.$tools.showtt(JSON.parse(res1.data).msg);
                      }
                    }
                  });
                })
                // });
              }
            });
          }
          if (index.tapIndex === 1) {
            uni.chooseFile({
              count: 1,
              type: 'file',
              success: (res) => {
                uni.uploadFile({
                  url: this.$tools.httpOne + 'utils/ossUpload',
                  filePath: res.tempFilePaths[0],
                  header: {
                    'Authorization': "Bearer " + sessionStorage.getItem('token')
                    // 'token': sessionStorage.getItem('token')
                  },
                  name: 'file',
                  success: (res1) => {
                    const data = JSON.parse(res1.data);
                    if (data.code === 200) {
                      const fileExtension = data.originalFilename.split('.').pop().toLowerCase();
                      const allowedExtensions = ['txt', 'pdf', 'doc', 'docx', 'ppt', 'xlsx', 'xls']; // 允许的文件扩展名列表
                      if (allowedExtensions.includes(fileExtension)) {
                        this.fileList.push({
                          fileName: data.originalFilename,
                          // fileType: JSON.parse(res1.data).originalFilename.split('.')[1],
                          fileType: '文件',
                          file: data.url,
                          // type: type
                        });
                      } else {
                        this.$tools.showtt('上传文件仅支持txt、pdf、word、excel、ppt');
                      }
                    } else {
                      this.$tools.showtt('上传失败');
                    }
                  }
                });
              }
            });
          }
          function checkFileSize(fileSize, maxSize) {
            if (fileSize > maxSize) {
              uni.showToast({
                title: `文件大小不能超过 ${maxSize / 1024 / 1024}MB`,
                icon: 'none'
              });
              return false;
            }
            return true;
          }
          if (index.tapIndex === 2) {
            if (this.fileList.find(v => v.fileType == '视频')) {
              this.$tools.showtt('最多只能上传一个视频');
              return
            }
            uni.chooseVideo({
              sourceType: ['album', 'camera'],
              compressed: true, // 启用自动压缩
              maxFileSize: 60 * 1024 * 1024, // 最大文件大小，单位为字节，这里是10MB
              success: (res) => {
                // 检查文件大小是否超过50MB
                if (!checkFileSize(res.size, 60 * 1024 * 1024)) {
                  return;
                }
                uni.uploadFile({
                  url: this.$tools.httpOne + 'utils/ossUpload',
                  filePath: res.tempFilePath,
                  name: 'file',
                  header: {
                    'Authorization': "Bearer " + sessionStorage.getItem('token')
                    // 'token': sessionStorage.getItem('token')
                  },
                  success: (res1) => {
                    if (JSON.parse(res1.data).code === 200) {
                      this.fileList.push({
                        fileName: JSON.parse(res1.data).originalFilename,
                        // fileType: JSON.parse(res1.data).originalFilename.split('.')[1],
                        fileType: '视频',
                        file: JSON.parse(res1.data).url,
                        // type: type
                      });
                    } else {
                      this.$tools.showtt('上传失败');
                    }
                  }
                });
              }
            });
          }
        }
      });

    },
    // 图片压缩函数
    compressImage(filePath) {
      return new Promise((resolve, reject) => {
        uni.getImageInfo({
          src: filePath,
          success: (imageInfo) => {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            const img = new Image();

            img.onload = () => {
              const MAX_WIDTH = 800; // 最大宽度
              const MAX_HEIGHT = 800; // 最大高度
              let width = img.width;
              let height = img.height;

              if (width > height && width > MAX_WIDTH) {
                height = (height / width) * MAX_WIDTH;
                width = MAX_WIDTH;
              } else if (height > width && height > MAX_HEIGHT) {
                width = (width / height) * MAX_HEIGHT;
                height = MAX_HEIGHT;
              }

              canvas.width = width;
              canvas.height = height;
              ctx.drawImage(img, 0, 0, width, height);

              canvas.toBlob((blob) => {
                const newFilePath = URL.createObjectURL(blob);
                resolve(newFilePath);
              }, 'image/jpeg', 0.8); // 压缩质量
            };
            img.src = imageInfo.path;
          },
          fail: (err) => {
            reject(err);
          }
        });
      });
    },
    getDate() {
      const now = new Date();

      const year = now.getFullYear();  // 获取年份
      const month = String(now.getMonth() + 1).padStart(2, '0');  // 获取月份，月从 0 开始，所以需要加 1，使用 padStart 补充零
      const day = String(now.getDate()).padStart(2, '0');  // 获取日期，使用 padStart 补充零

      const hours = String(now.getHours()).padStart(2, '0');  // 获取小时，补充零
      const minutes = String(now.getMinutes()).padStart(2, '0');  // 获取分钟，补充零
      const seconds = String(now.getSeconds()).padStart(2, '0');  // 获取秒数，补充零

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    submit(type) {
      this.practiceData.pointsCap = this.integralList[this.integralIndex];
      this.practiceData.taskNumber = this.taksnNumList[this.taksnNumIndex];
      if (!this.practiceData.taskName) return this.$tools.showtt('任务名称不能为空')
      if (this.scoreIndex == null) return this.$tools.showtt('请选择任务类型')
      if (this.integralIndex == null) return this.$tools.showtt('请选择积分上限')
      if (this.range.length == 0) return this.$tools.showtt('请选择任务时间')
      if (this.practiceData.participationWay == 2 && this.practiceData.applyCheck == null) return this.$tools.showtt('报名审核不得为空')
      if (!this.practiceData.taskRequire) return this.$tools.showtt('任务要求不得为空')
      // if(this.fileList.length ==0) return this.$tools.showtt('请上传文件')

      if (this.practiceData.participationWay == 2) {
        this.practiceData.taskNumber = 1;
        if (this.dateRangeApply.length == 0) return this.$tools.showtt('请选择报名时间')
        if (new Date(this.range[0] + ' 00:00:00') < new Date(this.dateRangeApply[0] + ' 00:00:00')) return this.$tools.showtt("报名开始时间必须在任务开始时间之前");
        if (new Date(this.range[1] + ' 23:59:59') < new Date(this.dateRangeApply[1] + ' 23:59:59')) return this.$tools.showtt("报名结束时间必须在任务结束时间之前");
        this.practiceData.applyStartTime = this.dateRangeApply[0] + ' 00:00:00';
        this.practiceData.applyEndTime = this.dateRangeApply[1] + ' 23:59:59';
      }
      this.practiceData.noPassPoints == null ? this.practiceData.noPassPoints = 0 : '';
      this.practiceData.peoplesNumberAstrict == null || this.practiceData.peoplesNumberAstrict == 0 ? this.practiceData.peoplesNumberAstrict = 1 : '';
      this.practiceData.applyPassCancelPoints == null ? this.practiceData.applyPassCancelPoints = 0 : '';

      let data = { ...this.practiceData, startTime: this.range[0] + ' 00:00:00', endTime: this.range[1] + ' 23:59:59', fileList: this.fileList };
      type === 1 ? data.releaseTime = this.getDate() : '';
      data.faceXy = (this.xyIdList || []).join(',');
      data.faceZy = (this.zyIdList || []).join(',');
      data.faceBj = (this.bjIdList || []).join(',');
      data.studentIds = this.studentIds;
      if (!this.taskId) {
        this.$tools.axiosFromToken('POST', 'project/task', { ...data, taskStatus: type }, '加载中').then(res => {
          if (res.code != 200) return this.$tools.showtt(res.msg)
          setTimeout(() => {
            this.$tools.goBack(1)
          }, 500)
        })
      } else {
        this.$tools.axiosFromToken('PUT', 'project/task', { ...data, taskStatus: type }, '加载中').then(res => {
          if (res.code != 200) return this.$tools.showtt(res.msg)
          setTimeout(() => {
            this.$tools.goBack(1)
          }, 500)
        })
      }
    }
  }
}
</script>

<style lang="scss">
page {
  background-color: #fff;
}

::v-deep .uni-card {
  margin-left: 5px !important;
  margin-right: 5px !important;
  overflow: visible;
}

::v-deep .uni-card__content {
  color: #000 !important;
  padding: 0 !important;
}

::v-deep .uni-date {
  flex: 1;

  .uni-date__icon-clear {
    border: 0 !important;
    top: 2px;
  }

  .uni-date-x--border {
    border: 0 !important;
  }
}

::v-deep .uni-flex-item {
  display: flex;
  align-items: center !important;
}

::v-deep .uni-date__x-input {
  width: 50% !important;
  height: auto !important;
  padding: 5px !important;
}

.inforClass {
  font-size: 16px;
  font-weight: 700;
  display: flex;
  align-items: center;
  margin: 8px 0;
}

.inforClass::before {
  content: '';
  width: 5px;
  height: 20px;
  background-color: #007AFF;
  margin-right: 5px;
  display: inline-block;
}

.mark {
  text-align: right;
  color: #f92929;
}

.practiceType {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 90rpx;
}

.border-botm {
  border-bottom: 1px #f1f1f1 solid;
}

::v-deep uni-button {
  padding-left: 10px !important;
  padding-right: 10px !important;
}

::v-deep .uni-stat__select {
  padding-right: 5px !important;
}

::v-deep .uni-stat__actived {
  width: 100% !important;
}

::v-deep .uni-select {
  display: block;
}

::v-deep .uni-input-wrapper {
  margin-right: 20px !important;
}

::v-deep .uni-input-input {
  padding-right: 35px !important;
}
</style>
